"""
环境变量： 名称：LINKAI_USER   如：手机号##密码
多账号新建变量或者用 & 分开
注册链接： https://chat.link-ai.tech/home?share=QPVkm8

定时：一天1-2次

更新日志：
2024-01-06

cron: 20 10 * * *
const $ = new Env("Link.AI");
"""
import os
import random
import time

import requests

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Authorization': 'Bearer',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Referer': 'https://link-ai.tech/home',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'
}


def get_token(username, password):
    url = 'https://link-ai.tech/api/login'
    payload = 'username=' + username + '&password=' + password
    res = requests.post(url=url, headers=headers, data=payload).json()
    if res['success'] is True and res['code'] == 200:
        print(res)
        time.sleep(random.randint(10, 30))
        return res['data']['token']
    else:
        print('登录失败！')
        print(res)
        exit()
    pass


def sign_in(token):
    url = 'https://link-ai.tech/api/chat/web/app/user/sign/in'
    headers['Authorization'] = 'Bearer ' + token
    res = requests.get(url=url, headers=headers).json()
    print(res)
    pass


def balance(token):
    url = 'https://link-ai.tech/api/chat/web/app/user/get/balance'
    headers['Authorization'] = 'Bearer ' + token
    res = requests.get(url=url, headers=headers).json()
    print(res)
    pass


if __name__ == '__main__':
    users = os.getenv('LINKAI_USER')
    if users is None:
        print('请先设置 LINKAI_USER 变量 格式：账号##密码')
        exit()

    users = users.split('&')

    for user in users:
        userArr = user.split('##')
        if len(userArr) != 2:
            continue

        auth_token = get_token(userArr[0], userArr[1])
        sign_in(auth_token)
        balance(auth_token)
